<template>
    <section>
        <!--添加和高级查询的工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="请输入部门"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="filters.state" placeholder="选择部门状态">
                        <el-option value="1" key="1" label="启用"></el-option>
                        <el-option value="0" key="0" label="禁用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadDepartment(1)">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--列表-->
        <!--departments：列表绑定的数据
            highlight-current-row:单选
            v-loading：显示加载框
            @selection-change：操作复选框触发的事件(方法)
            type="index"： 自动有编号，从1开始
        -->
        <el-table :data="departments" v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="80" label="编号">
            </el-table-column>
            <el-table-column prop="name" label="部门名">
            </el-table-column>
            <el-table-column prop="sn" label="部门编号">
            </el-table-column>
            <el-table-column prop="state" label="部门状态" :formatter="formatState">
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理">
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门">
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具栏-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove(sels)" :disabled="this.sels.length==0">批量删除</el-button>
            <el-pagination style="float: right" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage"
                           :page-sizes="pageSizes"
                           :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
        </el-col>

        <!--修改-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="editForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门状态">
                    <el-radio-group v-model="editForm.state">
                        <el-radio class="radio" :label="1">开启</el-radio>
                        <el-radio class="radio" :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!--managers：返回所有employee的集合-->
                <el-form-item label="部门经理">
                    <el-select v-model="editForm.managerId" placeholder="请选择">
                        <el-option

                                v-for="item in managers"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!--parentDepartments：返回所有上级部门的集合-->
                <el-form-item label="上级部门">
                    <el-select v-model="editForm.parentId" placeholder="请选择">
                        <el-option
                                v-for="item in parentDepartments"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>
    export default {
        data() {
            return {
                //部门经理
                managers: [],
                //上级部门列表
                parentDepartments: [],
                //高级查询属性
                filters: {
                    name: "",
                    state: "",
                },
                //添加校验
                editFormRules: {
                    name: [
                        {required: true, message: '请输入部门名称', trigger: 'blur'},
                        {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '请输入部门编号', trigger: 'blur'},
                        {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
                    ]
                },
                //加载的小圈圈
                editLoading: false,
                //模态框，默认为关闭状态
                editFormVisible: false,
                editForm: {
                    id: "",
                    name: "",
                    state: "",
                    sn: "",
                    //部门经理
                    managerId: "",
                    //上级部门
                    parentId: ""
                },
                //当前显示第一面
                currentPage: 1,
                //每页显示的条数
                pageSizes: [5, 10, 15, 20],
                //总数
                total: 0,
                //批量删除，要放在数组中
                sels: [],
                //每页展示的数据,默认为5条
                pageSize: 5,
                //列表数据
                departments: [],
                //默认加载框
                listLoading: false,
            }
        },
        methods: {
            //批量删除                          未完成
            batchRemove(val) {
                console.debug(11111111111111111111111111111111111);
                console.debug(val);
                let deletesParam = val

                this.$confirm('您确认要删除勾选的数据吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.patch("http://localhost:80/department/batchRemove", deletesParam).then((res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            //刷新页面
                            this.loadDepartment();
                        } else {
                            this.$message('删除失败哈哈哈!!!!');
                        }
                    }));
                })
            },
            selsChange(val) {
                console.debug(val)
                this.sels = val;
                console.debug(this.sels)
            },
            //添加
            handleAdd() {
                this.editFormVisible = true;
                //1.清楚缓存
                for (let k in this.editForm) {
                    this.editForm[k] = "";
                }
                this.editForm.state = 1;
            },
            //选择几条/页，触发该事件            完成
            handleSizeChange(val) {
                //每次都显示在第一页
                this.currentPage = 1;
                //1，定义选择第几页
                this.pageSize = val;
                //2.刷新列表
                this.loadDepartment();
            },
            //点击第几页，触发该事件             完成
            handleCurrentChange(val) {
                console.debug(val)
                this.currentPage = val;
                this.loadDepartment();
            },
            /*formatState格式化
            * row:当前对象
            * column:列属性，可以不用这个列属性
            * console.debug(row.state):  0表示禁用  1 表示启用
            * */                           //完成
            formatState(row) {

                return row.state == 1 ? "启用" : "禁用"
            },
            //选中复选框，操作此函数,参数为选中的第几行  完成
            //编辑的时候提交数据                 完成
            editSubmit() {
                //当form表单要进行提交的时候，必须要验证通过
                this.$refs.editForm.validate((valid) => {
                    //如果校验成功，则执行if代码块中的内容
                    if (valid) {
                        //如果id不为空字符串，则为添加
                        if (this.editForm.id) {
                            console.debug(11)
                            let updateParam = {
                                "id": this.editForm.id,
                                "sn": this.editForm.sn,
                                "name": this.editForm.name,
                                "state": this.editForm.state,
                                "manager": {
                                    id: this.editForm.managerId
                                },
                                "parent": {
                                    id: this.editForm.parentId
                                }
                            }
                            this.$http.post("http://localhost:80/department", updateParam).then((res => {
                                if (res.data.success) {
                                    this.$message({
                                        type: 'success',
                                        message: '修改成功!'
                                    });
                                    //刷新页面
                                    this.loadDepartment();
                                    this.editFormVisible = false
                                } else {
                                    this.$message('修改失败哈哈哈!!!!');
                                }
                            }))
                        } else {
                            let addParam = {
                                "sn": this.editForm.sn,
                                "name": this.editForm.name,
                                "state": this.editForm.state,
                                "manager": {
                                    id: this.editForm.managerId
                                },
                                "parent": {
                                    id: this.editForm.parentId
                                }
                            };
                            this.$http.put("http://localhost:80/department", addParam).then((res => {
                                if (res.data.success) {
                                    this.$message({
                                        type: 'success',
                                        message: '添加成功!'
                                    });
                                    //刷新页面
                                    this.loadDepartment();
                                    this.editFormVisible = false
                                } else {
                                    this.$message('添加失败哈哈哈!!!!');
                                }
                            }))
                        }
                    }
                });


            },
            //编辑的时候触发此函数，index和row    完成
            handleEdit(index, row) {
                //先清空form表单，再赋值
                for(let k in this.editForm){
                    this.editForm[k] = "";
                }
                //1.点击编辑弹出模态框
                this.editFormVisible = true;
                //2.回显数据
                for (let k in row){
                    this.editForm[k]=row[k];
                }
                //3.回显上级部门
                if(this.editForm.parent){
                    this.editForm.parentId=this.editForm.parent.id
                }
                //4.回显部门经理
                if(this.editForm.manager){
                    this.editForm.managerId=this.editForm.manager.id
                }
            },
            //点击删除，触发此函数                完成
            handleDel(index, row) {
                console.debug("我要删除的对象是")
                console.debug(row.id)
                this.$confirm('您确认离我而去吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("http://localhost:80/department/" + row.id).then((res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            //刷新页面
                            this.loadDepartment();
                        } else {
                            this.$message('删除失败哈哈哈!!!!');
                        }
                    }));
                })
            },
            //加载部门员工                       完成
            loadDepartment(val) {
                if (val != null) {
                    this.currentPage = val;
                }
                let departParam = {
                    "currentPage": this.currentPage,
                    "pageSize": this.pageSize,
                    "name": this.filters.name,
                    "state": this.filters.state
                };
                this.$http.patch("http://localhost:80/department", departParam).then((res => {
                    console.debug("后台回显数据", res)
                    //请求之前显示加载框
                    this.listLoading = true;
                    this.departments = res.data.list;
                    this.total = res.data.total;
                    //请求之后显示加载框
                    this.listLoading = false;
                }))
            },
            //部门经理
            loadManagers() {
                /*this.$http.patch("http://localhost/employee").then((res => {
                    console.debug("部门经理", res)
                    this.managers = res.data;
                }));*/
                this.$http.patch("http://localhost/employee/manageAll").then((res=>{
                    console.debug("部门经理",res)
                    this.managers = res.data;
                }))
            },
            //上级部门列表
            loadParentDepartments() {
                this.$http.patch("http://localhost/department/loadParentAll").then((res => {
                    console.debug("上级部门", res)
                    this.parentDepartments = res.data;
                }));
            }
        },
        mounted() {  //入口函数
            /*发送部门列表
            * 跨域问题：只针对ajax的一种限制，只要协议，域名，端口有任何一个不同，都属于跨域
            * 跨域不一定会有跨域问题：同步请求
            * */
            this.loadDepartment();
            this.loadManagers();
            this.loadParentDepartments();
        }
    }

</script>